#include "my_can.h"
// extern uint8_t can_buff[8];

void my_can_init(void)
{
	twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(can_tx_io,can_rx_io, can_mode);//io，以及模式等配置
	twai_timing_config_t t_config = can_baud;//波特率设置
	twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();//过滤器设置为接收所有id

	//Install TWAI driver
	if (twai_driver_install(&g_config, &t_config, &f_config) == ESP_OK){
		printf("CAN Driver installed\n");
	}
	else{
		printf("CAN Failed to install driver\n");
	}
	//Start TWAI driver
	if (twai_start() == ESP_OK){
		printf("CAN Driver started\n");
	}
	else{
		printf("CAN Failed to start driver\n");
	}
	xTaskCreatePinnedToCore(CAN_Receive_Task,"CAN_Receive_Task",4096,NULL,1,NULL,tskNO_AFFINITY);
}


void CAN_Send_Task(uint32_t can_id,uint8_t can_len,uint8_t *msg)
{
	twai_message_t  can_tx_message;
	can_tx_message.identifier=can_id;
	can_tx_message.data_length_code=can_len;
	for(uint8_t i=0;i<can_len;i++)
	{
		can_tx_message.data[i]=msg[i];
	}
	// {.identifier = 0x200, .data_length_code = 8,
    //                                         .data = {1, 2 , 3 , 4 ,5 ,6 ,7 ,8}};
    if((twai_transmit(&can_tx_message, pdMS_TO_TICKS(1000))==ESP_OK))
	{
		printf("CAN send OK\n");
	}   
}

void CAN_Receive_Task(void *arg)
{
	twai_message_t  can_rx_message;
    while(1)
    {
        if(twai_receive(&can_rx_message, pdMS_TO_TICKS(1000))==ESP_OK)
        {
			for(uint8_t i=0;i<8;i++)
			{
				can_buff[i]=can_rx_message.data[i];
			}
            CAN_Send_Task(can_rx_message.identifier,8, can_buff);
        }
        vTaskDelay(50);
    }
}
